package com.aaa.zs.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.RequestContent;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class IllegalIPFilter extends ZuulFilter {
    @Value("${illegal_ip}")
    private String illegalIp;
    @Override
    public String filterType() {
        //过滤器的适用类型
        /*
            pre 在调用后台微服务中业务方法之前
            route 在调用后台微服务中业务方法时
            post 在调用后台微服务中业务方法之后
            error 在调用后台微服务中业务方法出现异常
         */
        return "pre";
    }

    @Override
    public int filterOrder() {
        //多个filter时，当前filter执行的优先级 返回值越小，优先级越高 越先执行
        return 5;
    }

    @Override
    public boolean shouldFilter() {
        //是否让当前过滤器失效 true 生效 false 失效
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //具体过滤业务代码
        System.out.println("进入了IP过滤器。。。。");
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取请求用户的IP地址
        HttpServletRequest request=currentContext.getRequest();
        HttpServletResponse response = currentContext.getResponse();
        String remoteAddr = request.getRemoteAddr();
        System.out.println("ip"+remoteAddr);
        //判断IP是否合法
        System.out.println(illegalIp);
        if(illegalIp.contains(remoteAddr)){
            //阻止程序运行
            currentContext.setSendZuulResponse(false);
            //添加响应方式
            try {
                response.sendError(HttpStatus.SC_FORBIDDEN,"你的IP非法，不能访问该网站");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
